package com.shaohai.live.utils;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.shaohai.live.entity.jsonResult;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public abstract class JsonResultCallBack<T> implements Callback {

    public abstract void onResponseSuccess(T result);

    public abstract void onResponseError(String error);

    @Override
    public void onFailure(Call call, IOException e) {
        onResponseError("请求失败，".concat(e.getMessage() + ""));
    }

    @Override
    public void onResponse(Call call, Response response) {
        if (response.isSuccessful() && response.body() != null) {
            String responseString = response.body().toString();
            try {
                Gson gson = new Gson();
                jsonResult<T> result = gson.fromJson(responseString, new TypeToken<jsonResult<T>>() {
                }.getType());
                if (result != null && result.respCode.equals("200")) {
                    onResponseSuccess(result.data);
                } else if (result != null && !StringUtils.isNullOrEmpty(result.respMessage)) {
                    onResponseError(result.respMessage);
                } else {
                    onResponseError("请求失败".concat(String.valueOf(response.code())).concat(response.message()));
                }
            } catch (JsonParseException ex) {
                onResponseError("数据解析失败，请稍后重试！");
            }
        } else {
            onResponseError("网络连接失败，请稍后重试！");
        }
    }
}